package com.lagou.listener;

import com.lagou.entity.Order;
import com.lagou.entity.Stock;
import com.lagou.service.OrderService;
import com.lagou.service.StockService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 13771
 * @date 2021/1/15 16:36
 * @description
 */
@Component
@RocketMQMessageListener(topic = "springboot-mq",consumerGroup = "springboot-mq-consumer-1")
public class MyRocketMqListener implements RocketMQListener<Order> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StockService stockService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onMessage(Order order) {

        orderService.saveOrUpdate(order);

        Stock stock = stockService.findById(order.getStockId());
        Integer restNum = stock.getNum()- 1;
        stock.setNum(restNum);
        System.out.println(order.getId()+"号订单入库，扣减库存，剩余库存："+ restNum);
        //更新库存
        stockService.saveOrUpdate(stock);

        //将该订单id存入redis中，设置过期时间
        redisTemplate.opsForValue().set("order:"+order.getId(),"",15, TimeUnit.SECONDS);
    }
}
